package cn.yuanqiao.archive.report.filter;/**
 * @author 赵常飞
 * @date 2022/11/11 15:33
 */

import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 *
 *@AUTHOR:Administrator
 */
@Component
public class HeaderFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String requestjson=servletRequest.getParameter("json")==null?"":servletRequest.getParameter("json");
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request);
        if("".equals(requestjson)){
            //json不存在时,Authorization一定会存在,网关处有限制
            mutableRequest.putHeader("TenantId", request.getHeader("TenantId"));
        }else{
            sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
            byte[] buffer = decoder.decodeBuffer(requestjson);
            //指定utf-8解码
            String jsonString=new String(buffer,"utf-8");
            JSONObject json=JSONObject.parseObject(jsonString);
            HttpSession session = mutableRequest.getSession();
            session.setAttribute("UserID", json.get("UserID"));
            session.setAttribute("UserName", json.get("UserName"));
            session.setAttribute("tenantId", json.get("TenantCode"));
            session.setMaxInactiveInterval(10*60*1000);
            mutableRequest.putHeader("tenantId", String.valueOf(json.get("TenantCode")));
        }
        filterChain.doFilter(mutableRequest,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
